@echo off
chcp 65001 >nul
set PYTHON_SCRIPT=main.py
set SCRIPT_TITLE=PYTHON CONTROLLER

:: 新增命令行参数处理
if "%1"=="start" goto start_python
if "%1"=="stop" goto stop_python
if "%1"=="status" goto check_status

:menu
cls
echo ==============%SCRIPT_TITLE%==============
echo.
echo  1. Start Python Program
echo  2. Stop Python Program
echo  3. Exit
echo.
set /p choice=Please enter the option number:
if "%choice%"=="1" goto start_python
if "%choice%"=="2" goto stop_python
if "%choice%"=="3" exit

:start_python
echo Checking Python environment...
where python >nul 2>&1
if %errorlevel% neq 0 (
    echo Error: Python not found, please install Python and add to system path
    pause
    goto menu
)

echo Starting %PYTHON_SCRIPT%...
start "PythonProgramWindow" python %PYTHON_SCRIPT%
timeout /t 1 >nul

:: 精确获取PID
set PID=
for /f "tokens=2 delims=," %%i in ('tasklist /v /nh /fi "windowtitle eq PythonProgramWindow*" /fo csv ^| find "python.exe"') do (
    set PID=%%~i
)
echo %PID% > python_pid.tmp
echo Program started! PID: %PID%
timeout /t 1 >nul
goto menu

:stop_python
echo Stopping %PYTHON_SCRIPT%...
if exist python_pid.tmp (
    set /p PID=<python_pid.tmp
    taskkill /f /pid %PID% >nul 2>&1
    if %errorlevel% == 0 (
        echo Process %PID% terminated
    ) else (
        echo No running process found
    )
    del python_pid.tmp
) else (
    echo No PID record found
)
pause
goto menu

:check_status
if exist python_pid.tmp (
    set /p PID=<python_pid.tmp
    tasklist /fi "PID eq %PID%" | find "python.exe" >nul
    if %errorlevel% == 0 (
        echo 程序正在运行 PID: %PID%
    ) else (
        echo 程序未运行（残留PID记录）
    )
) else (
    echo 程序未运行
)
exit /b 